package com.barbeque.mall.controller;

import com.barbeque.mall.anno.Log;
import com.barbeque.mall.bean.*;
import com.barbeque.mall.bean.system.MarketAdmin;
import com.barbeque.mall.bean.system.MarketPermission;
import com.barbeque.mall.bean.system.MarketRole;
import com.barbeque.mall.service.AdminAuthService;
import com.barbeque.mall.util.Constant;
import com.barbeque.mall.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    AdminAuthService adminAuthService;



    /**
     * Shiro
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @Log(action = "登录")
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) throws NoSuchAlgorithmException {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        //对密码进行md5散列
        String md5 = MD5Utils.getMd5(password, Constant.SALT);

        //在这里要执行登陆，Subject.login
        //->Subject只能作为局部变量，不能作为全局变量
        //在方法里使用
        Subject subject = SecurityUtils.getSubject();
        //执行登陆（认证）
        UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username, md5);
        try {
            //realm.doGetAuthenticationInfo
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
           return BaseRespVo.errorNamePsg("用户名，密码不正确");
        }
        //判断是否认证成功
        boolean authenticated = subject.isAuthenticated();
        //可以获得session信息，也可以获得sessionId
        Session session = subject.getSession();
        //获得Principal信息->realm的doGetAuthorizationInfo方法构造的认证信息里的第一个参数
        // MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();

//        adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        adminInfo.setNickName("admin123");
        loginUserData.setAdminInfo(adminInfo);
        //loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        loginUserData.setToken((String) session.getId());
        //响应sessionId信息给到前端，前端发送请求的时候，通过请求头携带了session的id信息

        return BaseRespVo.ok(loginUserData);
    }





    @RequestMapping("info")
    public BaseRespVo info(String token) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            InfoData infoData = new InfoData();
            MarketAdmin marketAdmin = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
            infoData.setAvatar(marketAdmin.getAvatar());
            infoData.setName(marketAdmin.getUsername());
            Integer[] roleIds = marketAdmin.getRoleIds();
            ArrayList<String> perms = new ArrayList<>();
            ArrayList<String> rolesS = new ArrayList<>();
            for (Integer roleId : roleIds) {
//                 List<MarketPermission> permissionByRoleId = adminAuthService.getPermissionByRoleId(roleId);
                List<String> apiByRoleId = adminAuthService.getApiByRoleId(roleId);

//                 for (MarketPermission marketPermission : permissionByRoleId) {
//                     String permission = marketPermission.getPermission();
//                     perms.add(permission);
//                 }

                for (String api : apiByRoleId) {
                    perms.add(api);
                }
                List<MarketRole> marketRoles = adminAuthService.getRoleIdName(roleId);
                for (MarketRole marketRole : marketRoles) {
                    String name = marketRole.getName();
                    rolesS.add(name);
                }
            }

            // List<String> permissions = perms;
            // List<String> roles = rolesS;
 //        InfoData infoData = new InfoData();
//        infoData.setPerms(perms);
            infoData.setRoles(rolesS);
            infoData.setPerms(perms);
            return BaseRespVo.ok(infoData);


        }
//        //开发完shiro之后，再整合
//        InfoData infoData = new InfoData();
//        //infoData.setName("admin123");
//
//        //根据primaryPrincipal做查询
//        //infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        ArrayList<String> roles = new ArrayList<>();
//        //roles.add("超级管理员");
//        infoData.setRoles(roles);
//        ArrayList<String> perms = new ArrayList<>();
//        perms.add("*");
//        infoData.setPerms(perms);


        return BaseRespVo.unAuthc();
    }

    @RequestMapping("logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok(Constant.SUCCESS_CODE);
    }
}
